package com.tanhua.server.service;

import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.Movements;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VisitorsVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.RelativeDateFormat;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MovementsService {

    @Reference
    private PublishApi publishApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VisitorsApi visitorsApi;

    @Autowired
    private MovementsMqService movementsMqService;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送动态
     */
    public ResponseEntity saveMovements(Publish publish, MultipartFile[] imageContent) throws IOException {
        //1、将文件上传到阿里云OSS上
        //2、获取图片的请求路径
        List<String> medias = new ArrayList<>();
        if(imageContent != null) {
            for (MultipartFile file : imageContent) {
                String imageUrl = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
                medias.add(imageUrl);
            }
        }
        //3、设置到publish对象中
        publish.setMedias(medias);
        //调用API发布松台
        String id = publishApi.save(publish);


        try {
            //发送MQ消息 (消息 = 动态ID)
            rocketMQTemplate.convertAndSend("tanhua-publish",id);
            //发送动态推荐消息
            movementsMqService.publishMsg(id);
        }catch (Exception e) {}


        return ResponseEntity.ok(null);
    }

    /**
     * 查询好友动态
     */
    public ResponseEntity queryUserPublishList(Integer page, Integer pagesize) {
        //1、获取登录用户的ID
        Long userId = UserHolder.getUserId();
        //2、调用api完成分页查询   publish对象
        PageResult result = publishApi.findAllByTimeline(page, pagesize, userId);
        //3、获取publish列表
        List<Publish> items = (List<Publish>) result.getItems();
        //4、一个publish构造成一个Movements
        List<Movements> list = new ArrayList<>();
        if(items != null) {
            for (Publish item : items) {
                Movements vo = new Movements();
                UserInfo userInfo = userInfoApi.findById(item.getUserId());
                if(userInfo != null) {
                    BeanUtils.copyProperties(userInfo,vo);
                    if(userInfo.getTags() != null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                BeanUtils.copyProperties(item, vo);
                vo.setId(item.getId().toHexString());
                vo.setCreateDate(RelativeDateFormat.format(new Date(item.getCreated())));
                if(redisTemplate.hasKey("publish_like_comment_"+userId+"_"+item.getId().toHexString())) {
                    vo.setHasLiked(1);  //是否点赞  0：未点 1:点赞
                }else{
                    vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
                }

                if(redisTemplate.hasKey("publish_love_comment_"+userId+"_"+item.getId().toHexString())) {
                    vo.setHasLoved(1);  //是否喜欢  0：未点 1:点赞
                }else {
                    vo.setHasLoved(0);  //是否喜欢  0：未点 1:点赞
                }
                vo.setImageContent(item.getMedias().toArray(new String[]{}));
                vo.setDistance("50米");
                list.add(vo);
            }
        }
        //5、构造返回值
        result.setItems(list);
        return ResponseEntity.ok(result);
    }

    /**
     * 从redis查询推荐数据
     *  查询第一页，每页5条
     */
    public PageResult findByRecommend(Integer page, Integer pagesize) {
        //1、拼接redis中的key
        String key = "QUANZI_PUBLISH_RECOMMEND_"+UserHolder.getUserId();
        //2、从redis中获取数据
        String value = redisTemplate.opsForValue().get(key);
        //3、判断数据是否存在，如果不存在，返回null
        if(StringUtils.isEmpty(value)) {
            return null;
        }
        //4、如果数据存在，构造PageResult对象
        String pids[] = value.split(","); //1,2,3,4,5,6,7,8,9,10
        Integer counts = pids.length;
        int startIndex = (page - 1) * pagesize; //计算本页的起始条数

        if(startIndex < pids.length) { //起始条数大于数据总数
            int endIndex = startIndex + pagesize - 1;
            if (endIndex >= pids.length) {
                endIndex = pids.length - 1;
            }
            List<Long> pidList = new ArrayList<>();   //本页查询的所有动态的pid列表
            for (int i = startIndex; i <= endIndex; i++) {
                pidList.add(Long.valueOf(pids[i]));
            }
            //本次分页的数据列表
            List<Publish> list = publishApi.findByPids(pidList);
            return new PageResult(page, pagesize, counts, list);
        }
        return null;
    }

    //查询推荐动态
    public ResponseEntity queryRecommendPublishList(Integer page, Integer pagesize) {
        //1、获取登录用户的ID
        Long userId = UserHolder.getUserId();
        //2、调用api完成分页查询   publish对象
        //a.查询redis中的数据（真正的推荐数据）
        PageResult result = findByRecommend(page,pagesize);
        if(result == null) {
            //b.查询默认的数据
            result = publishApi.findAllByRecommend(page, pagesize, userId); //默认数据
        }
        //3、获取publish列表
        List<Publish> items = (List<Publish>) result.getItems();
        //4、一个publish构造成一个Movements
        List<Movements> list = new ArrayList<>();
        if(items != null) {
            for (Publish item : items) {
                Movements vo = new Movements();
                UserInfo userInfo = userInfoApi.findById(item.getUserId());
                if(userInfo != null) {
                    BeanUtils.copyProperties(userInfo,vo);
                    if(userInfo.getTags() != null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                BeanUtils.copyProperties(item, vo);
                vo.setId(item.getId().toHexString());
                vo.setCreateDate(RelativeDateFormat.format(new Date(item.getCreated())));
                if(redisTemplate.hasKey("publish_like_comment_"+userId+"_"+item.getId().toHexString())) {
                    vo.setHasLiked(1);  //是否点赞  0：未点 1:点赞
                }else{
                    vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
                }
                if(redisTemplate.hasKey("publish_love_comment_"+userId+"_"+item.getId().toHexString())) {
                    vo.setHasLoved(1);  //是否喜欢  0：未点 1:点赞
                }else {
                    vo.setHasLoved(0);  //是否喜欢  0：未点 1:点赞
                }
                vo.setImageContent(item.getMedias().toArray(new String[]{}));
                vo.setDistance("50米");
                list.add(vo);
            }
        }
        //5、构造返回值
        result.setItems(list);
        return ResponseEntity.ok(result);
    }

    /**
     * 查询自己的动态
     */
    public ResponseEntity queryAlbumList(Integer page, Integer pagesize, Long userId) {
        //1、调用API查询
        PageResult result = publishApi.findAllByAlbum(page,pagesize,userId);
        //2、获取到所有的动态明细列表 List<Publish>
        List<Publish> items = (List<Publish>) result.getItems();
        //3、循环所有的动态明细
        List<Movements> list = new ArrayList<>();
        for (Publish item : items) {
            //4、一个publish创建一个movenments对象（a.用户信息，b.动态明细）
            Movements vo = new Movements();
            //5、查询用户明细
            UserInfo userInfo = userInfoApi.findById(item.getUserId());
            //6、组装数据
            if(userInfo != null) {
                BeanUtils.copyProperties(userInfo,vo);
                if(userInfo.getTags() != null) {
                    vo.setTags(userInfo.getTags().split(","));
                }
            }
            BeanUtils.copyProperties(item, vo);
            vo.setId(item.getId().toHexString());
            vo.setCreateDate(RelativeDateFormat.format(new Date(item.getCreated())));
            if(redisTemplate.hasKey("publish_like_comment_"+userId+"_"+item.getId().toHexString())) {
                vo.setHasLiked(1);  //是否点赞  0：未点 1:点赞
            }else{
                vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
            }
            if(redisTemplate.hasKey("publish_love_comment_"+userId+"_"+item.getId().toHexString())) {
                vo.setHasLoved(1);  //是否喜欢  0：未点 1:点赞
            }else {
                vo.setHasLoved(0);  //是否喜欢  0：未点 1:点赞
            }
            vo.setImageContent(item.getMedias().toArray(new String[]{}));
            vo.setDistance("50米");
            list.add(vo);
        }
        result.setItems(list);
        //7、构造返回
        return ResponseEntity.ok(result);
    }

    /**
     * 根据动态id。查询动态详情
     */
    public ResponseEntity queryMovementsById(String publishId) {
        //1、调用api查询动态详情 ： publish
        Publish publish = publishApi.findById(publishId);
        //2、创建vo对象
        Movements vo = new Movements();
        //3、查询用户详情（发布人）
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        Long userId = publish.getUserId();
        //4、构造数据
        if(userInfo != null) {
            BeanUtils.copyProperties(userInfo,vo);
            if(userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        BeanUtils.copyProperties(publish, vo);
        vo.setId(publish.getId().toHexString());
        vo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
        if(redisTemplate.hasKey("publish_like_comment_"+userId+"_"+publishId)) {
            vo.setHasLiked(1);  //是否点赞  0：未点 1:点赞
        }else{
            vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
        }
        if(redisTemplate.hasKey("publish_love_comment_"+userId+"_"+publishId)) {
            vo.setHasLoved(1);  //是否喜欢  0：未点 1:点赞
        }else {
            vo.setHasLoved(0);  //是否喜欢  0：未点 1:点赞
        }
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        vo.setDistance("50米");
        //5、构造返回
        return ResponseEntity.ok(vo);
    }

    /**
     * 查询用户的访客记录
     *  1、访客记录，最多展示5条
     *  2、记录本次查询的时间
     */
    public ResponseEntity queryVisitors() {
        //1、获取当前用户ID
        Long userId = UserHolder.getUserId();
        //2、从redis中获取，上次访问时间
        String key = "visitors_time_"+userId;
        String time = redisTemplate.opsForValue().get(key);
        List<Visitors> list = new ArrayList<>();
        if(!StringUtils.isEmpty(time)) {
            //3.1 redis中存在访问时间,调用API查询 （查询访客时间 > date）
            list = visitorsApi.topVisitors(userId,Long.valueOf(time));
        }else{
            //3.2 redis中不存在，查询所有的房客记录中的前5条    visitors对象  -- vo
            list = visitorsApi.topVisitors(userId,5);
        }
        //4、记录本次查询时间
        redisTemplate.opsForValue().set(key,System.currentTimeMillis()+"");
        //5、数据转化
        List<VisitorsVo>  voList = new ArrayList<>();
        for (Visitors visitors : list) {
            UserInfo info = userInfoApi.findById(visitors.getVisitorUserId());
            VisitorsVo visitorsVo = new VisitorsVo();
            BeanUtils.copyProperties(info,visitorsVo);
            visitorsVo.setTags(StringUtils.split(info.getTags(), ','));
            visitorsVo.setFateValue(visitors.getScore().intValue());
            voList.add(visitorsVo);
        }
        return ResponseEntity.ok(voList);
    }
}
